package com.ibm.psbc.cloud;


import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.property.SentinelProperty;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author Johnny
 */
@Configuration
public class GatewayConfiguration {
    private final List<ViewResolver> viewResolvers;
    private final ServerCodecConfigurer serverCodecConfigurer;

    @Value("${spring.cloud.nacos.discovery.server-addr}")
    String nacosAddress;
    @Value("${app.config.gateway.nacos.namespace:}")
    String namespace;
    static String groupId = "Spring-Gateway-Sentinel";
    static String flowRuleDataId = "FlowControlRules";
    static String apiDefDataId = "ApiDefinitions";
    static String degradeRuleDataId = "DegradeRules";

    public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                ServerCodecConfigurer serverCodecConfigurer) {
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        // Register the block exception handler for Spring Cloud Gateway.
        return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
    }

    @Bean
    @Order(-1)
    public GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }

    @PostConstruct
    public void doInit() {
        Properties nacosProps = new Properties();
        nacosProps.put(PropertyKeyConst.SERVER_ADDR, nacosAddress);
        nacosProps.put(PropertyKeyConst.NAMESPACE, namespace);
        loadApiDefs(nacosProps);
        loadFlowRules(nacosProps);
        loadDegradeRules(nacosProps);
    }
    ObjectMapper om =  new ObjectMapper().setSerializationInclusion(Include.NON_NULL);
    private void loadApiDefs(Properties nacosProps) {
    	ParserConfig parserConfig = new ParserConfig() {
            @Override
            public ObjectDeserializer getDeserializer(Type type) {
                if (type == ApiPredicateItem.class) {
                    return super.getDeserializer(ApiPathPredicateItem.class);
                }
                return super.getDeserializer(type);
            }
        };
        ReadableDataSource<String, Set<ApiDefinition>> dataSource = new NacosDataSource<>(nacosProps, groupId, apiDefDataId,
        		source -> JSON.parseObject(source, new TypeReference<Set<ApiDefinition>>() {
                }.getType(), parserConfig));
        SentinelProperty<Set<ApiDefinition>> prop = dataSource.getProperty();
		GatewayApiDefinitionManager.register2Property(prop);
    }
    private void loadFlowRules(Properties nacosProps) {
        ReadableDataSource<String, Set<GatewayFlowRule>> dataSource = new NacosDataSource<>(nacosProps, groupId, flowRuleDataId,
                source -> JSON.parseObject(source, new TypeReference<Set<GatewayFlowRule>>() {
                }));
        SentinelProperty<Set<GatewayFlowRule>> property = dataSource.getProperty();
		GatewayRuleManager.register2Property(property);
    }
    /**
     * 
     */
    private void loadDegradeRules(Properties nacosProps) {
        ReadableDataSource<String, List<DegradeRule> > dataSource = new NacosDataSource<>(nacosProps, groupId, degradeRuleDataId,
                source -> JSON.parseObject(source, new TypeReference<List<DegradeRule> >() {
                }));
        SentinelProperty<List<DegradeRule>> prop = dataSource.getProperty();
		DegradeRuleManager.register2Property(prop);
    }

}